package com.cqc.jdk8.Jtime;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @author cui
 * @date 2025/3/1 9:59
 * @description Duration：toMillis()方法，内部经过了计算；getNano()内部不需要计算
 **/
public class DurationTest {
    /**
     * 表示时间长度
     */
    @Test
    public void instance() {
        //视频长度为5分30秒
        Duration videoLength = Duration.ofMinutes(5).plusSeconds(30);
    }

    /**
     * 比较时间段
     */
    @Test
    public void compare() {
        //期待耗时30s
        Duration expected = Duration.ofSeconds(30);
        //实际耗时29s
        Duration actual = Duration.ofSeconds(29);
        if (actual.compareTo(expected) > 0) {
            System.out.println("不达标");
        } else {
            System.out.println("达标");
        }
    }

    /**
     * 计算时间差
     */
    @Test
    public void between() throws Exception {
        Instant startTime = Instant.now();
        TimeUnit.SECONDS.sleep(3);
        Instant endTime = Instant.now();
        long time = Duration.between(startTime, endTime).toMillis();
        System.out.println("耗时：" + time + "ms");
    }

    /**
     * LocalDateTime 增加一段时间
     */
    @Test
    public void plusX() {
        LocalDateTime now = LocalDateTime.now();
        Duration duration = Duration.ofHours(2).plusHours(2).plusMinutes(10);
        LocalDateTime newTime = now.plus(duration);
        String format = newTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println("时间：" + format);
    }


}
